# 用于访问OKCOIN 现货REST API
from lib.utilOkcoin import buildMySign, httpGet, httpPost, sort_and_format
from lib.settings import OKCOIN_API_URL
import config


'''
OkCoin现货交易
'''
class Okcoin(object):
    def __init__(self):  # url使用OKCOIN_API_URL['host']
        self.__url = OKCOIN_API_URL['host']
        self.__apikey = config.OKCOIN_API_KEY
        self.__secretkey = config.OKCOIN_SECRET_TOKEN
        self.fee = OKCOIN_API_URL['fee']

        self.btc_free = 0.0  # 账户情况
        self.btc_frozen = 0.0
        self.cny_free = 0.0
        self.cny_frozen = 0.0

        self.bid = 0.0  # 买一卖一情况
        self.bid_volume = 0.0
        self.ask = 0.0
        self.ask_volume = 0.0

    '''
    更新OKCOIN现货市场深度信息
    '''
    def update_depth(self):
        # 更新深度之前，先将上一次的深度置零
        self.bid = 0.0
        self.bid_volume = 0.0
        self.ask = 0.0
        self.ask_volume = 0.0
        try:
            response = httpGet(self.__url, OKCOIN_API_URL['depth'], 'symbol=btc_cny')
            if response and 'error_code' in response:  # response不为空，且有错误代码的存在；为空的原因可能是请求超时
                return False
            if not response:  # response为空
                return False
            self.bid = float(sort_and_format(response['bids'], True)[0]['price'])
            self.bid_volume = float(sort_and_format(response['bids'], True)[0]['volume'])
            self.ask = float(sort_and_format(response['asks'], False)[0]['price'])
            self.ask_volume = float(sort_and_format(response['asks'], False)[0]['volume'])
            return True
        except Exception as e:
            print(self.__class__.__name__ + ' update_depth error: ' + str(e))
            return False

    '''
    更新用户现货账户信息
    '''
    def update_accountInfo(self):
        # 更新账户资产之前，先将之前的置零
        self.btc_free = 0.0
        self.btc_frozen = 0.0
        self.cny_free = 0.0
        self.cny_frozen = 0.0
        try:
            params = {}
            params['api_key'] = self.__apikey
            params['sign'] = buildMySign(params, self.__secretkey)
            response = httpPost(self.__url, OKCOIN_API_URL['account_info'], params)
            if response and "error_code" in response:
                return False
            if not response:
                return False
            self.btc_free = float(response['info']['funds']['free']['btc'])
            self.btc_frozen = float(response['info']['funds']['freezed']['btc'])
            self.cny_free = float(response['info']['funds']['free']['cny'])
            self.cny_frozen = float(response['info']['funds']['freezed']['cny'])
            return True
        except Exception as e:
            print(self.__class__.__name__ + ' update_accountInfo error: ' + str(e))
            return False

    '''
    买入比特币
    '''
    def buy(self, price, amount):
        try:
            params = {
                'api_key': self.__apikey,
                'symbol': 'btc_cny',
                'type': 'buy'
            }
            if price:
                params['price'] = price
            if amount:
                params['amount'] = amount

            params['sign'] = buildMySign(params, self.__secretkey)
            response = httpPost(self.__url, OKCOIN_API_URL['trade'], params)
            if response and 'error_code' in response:  # response不为空，且有错误代码的存在；为空的原因可能是请求超时
                return False
            if not response:  # response为空
                return False

            return str(response['order_id'])
        except Exception as e:
            print(self.__class__.__name__ + ' buy error: ' + str(e))
            return False

    '''
    卖出比特币
    '''
    def sell(self, price, amount):
        try:
            params = {
                'api_key': self.__apikey,
                'symbol': 'btc_cny',
                'type': 'sell'
            }
            if price:
                params['price'] = price
            if amount:
                params['amount'] = amount

            params['sign'] = buildMySign(params, self.__secretkey)
            response = httpPost(self.__url, OKCOIN_API_URL['trade'], params)
            if response and 'error_code' in response:  # response不为空，且有错误代码的存在；为空的原因可能是请求超时
                return False
            if not response:  # response为空
                return False

            return str(response['order_id'])
        except Exception as e:
            print(self.__class__.__name__ + ' sell error: ' + str(e))
            return False

    '''
    现货订单信息查询
    '''
    def order_info(self, orderId):
        try:
            if not orderId:
                return False
            params = {
                'api_key': self.__apikey,
                'symbol': 'btc_cny',
                'order_id': orderId
            }
            params['sign'] = buildMySign(params, self.__secretkey)
            response = httpPost(self.__url, OKCOIN_API_URL['order_info'], params)
            if response and 'error_code' in response:
                return False
            if not response:
                return False
            if response['orders'][0]['status'] in (0, 1):
                return 'cancelable'
            else:
                return 'ircancelable'
        except Exception as e:
            print(self.__class__.__name__ + ' order_info error: ' + str(e))
            return False

    '''
    查询现货未成交订单
    '''
    def get_orders(self):
        try:
            params = {
                'api_key': self.__apikey,
                'symbol': 'btc_cny',
                'order_id': -1
            }
            params['sign'] = buildMySign(params, self.__secretkey)
            response = httpPost(self.__url, OKCOIN_API_URL['order_info'], params)
            if not response:
                return False
            if response and "error_code" in response:
                return False
            return response
        except Exception as e:
            print(self.__class__.__name__ + ' get_orders error: ' + str(e))
            return False

    '''
    取消订单
    '''
    def cancel_order(self, orderId):
        try:
            if not orderId:
                return False
            params = {
                'api_key': self.__apikey,
                'symbol': 'btc_cny',
                'order_id': orderId
            }
            params['sign'] = buildMySign(params, self.__secretkey)
            response = httpPost(self.__url, OKCOIN_API_URL['cancel_order'], params)
            if not response:
                return False
            if response and "error_code" in response:
                return False
            if response['result']:
                return True
            else:
                return False
        except Exception as e:
            print(self.__class__.__name__ + ' cancel_order error: ' + str(e))
            return False

    '''
    取消所有未成交订单
    '''
    def cancel_all(self):
        response = self.get_orders()
        if not response:
            return False
        for order in response['orders']:
            self.cancel_order(order['order_id'])
